<template>
  <a-modal
    :confirmLoading="confirmLoading"
    :maskClosable="true"
    :title="title"
    :visible="visible"
    :width="width"
    cancelText="关闭"
    destroyOnClose
    @cancel="handleCancel"
    @ok="handleOk"
  >
    <template slot="footer">
      <a-button icon="close" @click="handleCancel">关闭</a-button>
      <a-button v-if="!disableSubmit" icon="upload" type="primary" @click="handleOk">确定</a-button>
    </template>

    <a-spin :spinning="confirmLoading">
      <a-alert v-if="isImportConfig" :showIcon="true" style="margin-bottom: 20px;" type="info">
        <div slot="message">
          发现相似似告警配置，是否导入
          <a style="margin-left: 24px" @click="$refs.similarModal.visible=true">导入</a>
          <SimilarConfigModel ref="similarModal" :instanceSource="instanceSource" @ok="importConfig"/>
        </div>
      </a-alert>
      <a-form-model
        ref="alarmConfigForm"
        :label-col="labelCol"
        :model="model"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item v-show="false" ref="id" label="主键" prop="id">
          <a-input v-model="model.id" readOnly/>
        </a-form-model-item>
        <a-form-model-item ref="name" :rules="rules.name" label="告警名称" prop="name">
          <a-input v-model="model.name" placeholder="请输入告警名称"></a-input>
        </a-form-model-item>
        <a-form-model-item ref="instanceId" :rules="rules.instanceId" label="设备实例" prop="instanceId">
          <a-tree-select
            v-model="model.instanceId"
            :allow-clear="true"
            :disabled="instanceIdDisable"
            :tree-data="instanceTreeOptions"
            :triggers="true"
            placeholder="请选择设备实例"
          />
        </a-form-model-item>
        <a-form-model-item ref="triggerMethod" :rules="rules.triggerType" label="触发方式" prop="triggerMethod">
          <a-select
            v-model="model.triggerMethod"
            :getPopupContainer="(node) => node.parentNode"
          >
            <a-select-option key="device">设备触发</a-select-option>
            <a-select-option key="timer">定时检索</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item ref="alarmLevel" :rules="rules.alarmLevel" label="告警等级" prop="alarmLevel">
          <a-radio-group v-model="model.alarmLevel">
            <a-radio-button :value="1">一般</a-radio-button>
            <a-radio-button :value="2">严重</a-radio-button>
            <a-radio-button :value="3">危急</a-radio-button>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item ref="isDeal" :rules="rules.isDeal" label="是否处理" prop="isDeal">
          <a-radio-group v-model="model.isDeal">
            <a-radio :value="true">处理</a-radio>
            <a-radio :value="false">不处理</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item v-show="model.triggerMethod === 'timer'" ref="triggerCorn" label="定时表达式" prop="triggerCorn">
          <j-cron v-model="model.corn"></j-cron>
        </a-form-model-item>
        <a-form-model-item
          v-show="model.triggerMethod"
          ref="filterKey"
          label="匹配类型" prop="filterKey"
        >
          <a-radio-group v-model="model.triggerMatchType" size="small">
            <a-radio-button value="any">
              任意(any)
            </a-radio-button>
            <a-radio-button value="all">
              所有(all)
            </a-radio-button>
          </a-radio-group>
        </a-form-model-item>
        <!-- 触发规则 start -->
        <a-card
          v-for="(trigger, triggerIndex) in model.triggers"
          v-if="model.triggers"
          :key="trigger.id"
          size="small"
          style="margin: 10px 0 10px 0"
        >
          <template slot="title">
            <div style="display:flex;align-items:center">
              <span v-show="!model.triggers[triggerIndex].isNameEdit">{{ model.triggers[triggerIndex].name }}</span>
              <a
                v-show="!model.triggers[triggerIndex].isNameEdit"
                href="javascript:" @click="() => model.triggers[triggerIndex].isNameEdit = true">
                <a-icon style="font-size: 18px; margin-left: 4px" type="edit"/>
              </a>
              <a-input
                v-show="model.triggers[triggerIndex].isNameEdit"
                v-model="model.triggers[triggerIndex].name"
                style="width:200px"
                @blur="() => model.triggers[triggerIndex].isNameEdit = false"
              ></a-input>
              <a v-show="model.triggers[triggerIndex].isNameEdit"
                 href="javascript:"
                 @click="() => model.triggers[triggerIndex].isNameEdit = false">
                <a-icon style="font-size: 18px; margin-left: 4px" type="check"/>
              </a>
            </div>
          </template>
          <template slot="extra">
            <a v-if="model.triggers.length > 1" title="删除触发规则" @click="deleteTrigger(triggerIndex)">
              <a-icon theme="twoTone" two-tone-color="#eb2f96" type="close-circle" />
            </a>
          </template>
          <template>
            <a-form-model-item v-show="model.triggerMethod" label="消息源">
              <a-select
                v-model="model.triggers[triggerIndex].source"
                :getPopupContainer="(node) => node.parentNode"
                placeholder="请选择消息源"
              >
                <a-select-option
                  v-for="(source, index) in sourceOptions"
                  :key="source.code"
                  :disabled="source.disabled"
                >{{ source.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item
              v-show="model.triggerMethod && model.triggers[triggerIndex].source === 'data_receive'"
              ref="modelDataId"
              label="设备数据"
              prop="modelDataId"
            >
              <a-select
                v-model="model.triggers[triggerIndex].modelDataId"
                :getPopupContainer="(node) => node.parentNode"
                @change="val => updateFilterRule(triggerIndex, val)"
              >
                <a-select-option
                  v-for="(modelData, index) in modelDataOptions"
                  :key="modelData.id"
                >
                  {{ modelData.name }}({{ modelData.code }})
                </a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item
              v-show="model.triggerMethod"
              ref="filterValue"
              label="规则"
              prop="filterValue"
            >
              <template>
                <a-row style="margin-bottom:10px" type="flex">
                  <a-col :span="8">过滤属性</a-col>
                  <a-col :span="7">过滤规则</a-col>
                  <a-col :span="7">过滤值</a-col>
                  <a-col :span="2"></a-col>
                </a-row>
                <a-row v-for="(rule, ruleIndex) in model.triggers[triggerIndex].filters" :key="ruleIndex" :gutter="10" style="margin:0;" type="flex">
                  <a-col :span="8">
                    <!-- 过滤器的Key -->
                    <a-form-model-item>
                      <a-select
                        v-model="model.triggers[triggerIndex].filters[ruleIndex].filterKey"
                        :allowClear="true"
                        :getPopupContainer="(node) => node.parentNode"
                        mode="combobox"
                      >
                        <a-select-option v-for="filterKey in model.triggers[triggerIndex].filterRuleOptions" :key="filterKey">
                          {{ filterKey }}
                        </a-select-option>
                      </a-select>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="7">
                    <!-- 过滤器的Rule -->
                    <a-form-model-item>
                      <a-select
                        v-model="model.triggers[triggerIndex].filters[ruleIndex].filterRule"
                        :allowClear="true"
                        :getPopupContainer="(node) => node.parentNode"
                        placeholder="请选择过滤规则"
                      >
                        <a-select-option v-for="option in ruleConditionOptions" :key="option.value">
                          {{ option.text }}
                        </a-select-option>
                      </a-select>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="7">
                    <!-- 过滤器的Value -->
                    <a-form-model-item>
                      <a-input
                        v-model="model.triggers[triggerIndex].filters[ruleIndex].filterValue"
                        :allowClear="true"
                        placeholder="请输入过滤值" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="2">
                    <a-form-model-item>
                      <a title="删除规则条件" @click="delRowRule(triggerIndex, ruleIndex)">
                        <a-icon theme="twoTone" two-tone-color="#eb2f96" type="close-circle" />
                      </a>
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-row>
                  <a @click="addRowRule(triggerIndex)">
                    <a-icon type="plus" />
                    新增规则
                  </a>
                </a-row>
              </template>
            </a-form-model-item>
          </template>
        </a-card>
        <a href="#" style="margin: 10px 0 10px 0" @click="addTrigger">
          <a-icon style="font-size: 18px; margin-right: 4px" type="plus" />
          新增触发规则
        </a>
        <!-- 触发规则 end -->

        <!-- 执行器 start -->
        <a-card
          v-for="(actuator, actuatorIndex) in model.actuators"
          v-if="model.actuators"
          :key="actuator.id"
          size="small"
          style="margin: 10px 0 10px 0"
        >
          <template slot="title">
            <div style="display:flex;align-items:center">
              <span v-show="!actuator.isNameEdit">{{ actuator.name }}</span>
              <a
                v-show="!actuator.isNameEdit"
                href="javascript:" @click="() => actuator.isNameEdit = true">
                <a-icon style="font-size: 18px; margin-left: 4px" type="edit"/>
              </a>
              <a-input
                v-show="actuator.isNameEdit"
                v-model="actuator.name"
                style="width:200px"
                @blur="() => actuator.isNameEdit = false"
              ></a-input>
              <a v-show="actuator.isNameEdit"
                 href="javascript:"
                 @click="() => actuator.isNameEdit = false">
                <a-icon style="font-size: 18px; margin-left: 4px" type="check"/>
              </a>
            </div>
          </template>
          <template slot="extra">
            <a v-if="model.actuators.length > 1" title="删除执行器" @click="deleteActuator(actuatorIndex)">
              <a-icon theme="twoTone" two-tone-color="#eb2f96" type="close-circle" />
            </a>
          </template>
          <template>
            <a-form-model-item
              v-if="model.triggerMethod"
              :prop="'actuators.'+actuatorIndex+'.actuatorType'"
              :rules="[{ required: true, message: '请选择执行类型!' }]"
              label="执行类型"
            >
              <a-select
                v-model="actuator.actuatorType"
                :getPopupContainer="(node) => node.parentNode"
                allowClear
                placeholder="请选择执行类型"
              >
                <a-select-option v-for="actuatorType in actuatorTypeOptions" :key="actuatorType.value">{{ actuatorType.text }}</a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item
              v-if="model.triggerMethod && actuator.actuatorType === 1"
              :prop="'actuators.'+actuatorIndex+'.notification.noticeType'"
              :rules="[{
                required: model.triggerMethod && actuator.actuatorType === 1,
                message: '请选择通知类型!'
              }]"
              label="通知类型"
            >
              <a-select
                v-model="actuator.notification.noticeType"
                :getPopupContainer="(node) => node.parentNode"
                allowClear
                placeholder="请选择通知类型"
                @change="getSysMsgTemplate"
              >
                <template v-for="noticeTypeOpt in noticeTypeOptions">
                  <a-select-option :key="noticeTypeOpt.value">{{ noticeTypeOpt.text }}</a-select-option>
                </template>
              </a-select>
            </a-form-model-item>
            <a-form-model-item
              v-if="model.triggerMethod && actuator.actuatorType === 1 && actuator.notification.noticeType && actuator.notification.noticeType !== 4"
              :prop="'actuators.'+actuatorIndex+'.notification.noticeConfigId'"
              :rules="[{
                required: model.triggerMethod && actuator.actuatorType === 1  && actuator.notification.noticeType && actuator.notification.noticeType !== 4,
                message: '请选择通知配置!'
              }]"
              label="通知配置"
            >
              <a-select
                v-model="actuator.notification.noticeConfigId"
                :getPopupContainer="(node) => node.parentNode"
                allowClear
                placeholder="请选择通知配置"
              >
                <a-select-option v-for="noticeConfig in noticeConfigOptions" :key="noticeConfig.value">{{ noticeConfig.text }}</a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item
              v-if="model.triggerMethod && actuator.actuatorType === 1"
              :prop="'actuators.'+actuatorIndex+'.notification.noticeTemplateCode'"
              :rules="[{
                required: model.triggerMethod && actuator.actuatorType === 1,
                message: '请选择通知模板!'
              }]"
              label="通知模板"
            >
              <a-select
                v-model="actuator.notification.noticeTemplateCode"
                :getPopupContainer="(node) => node.parentNode"
                placeholder="请选择通知模板"
              >
                <a-select-option v-for="noticeTemplate in noticeTemplates" :key="noticeTemplate.code">{{ noticeTemplate.name }}</a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item
              v-if="model.triggerMethod && actuator.actuatorType === 2"
              :prop="'actuators.'+actuatorIndex+'.invokeFunction.instanceId'"
              :rules="[{
                required: model.triggerMethod && actuator.actuatorType === 2,
                message: '请选择设备实例!'
              }]"
              label="设备选择"
            >
              <a-tree-select
                v-model="actuator.invokeFunction.instanceId"
                :allow-clear="true"
                :tree-data="instanceTreeOptions"
                :triggers="true"
                placeholder="请选择设备实例"
                @change="val => updateDeviceFunction(actuatorIndex, val)"
              />
            </a-form-model-item>
            <a-form-model-item
              v-if="model.triggerMethod && actuator.actuatorType === 2"
              :prop="'actuators.'+actuatorIndex+'.invokeFunction.functionId'"
              :rules="[{
                required: model.triggerMethod && actuator.actuatorType === 2,
                message: '请选择设备功能!'
              }]"
              label="设备功能"
            >
              <a-select
                v-model="actuator.invokeFunction.functionId"
                :getPopupContainer="(node) => node.parentNode"
                allowClear
                placeholder="请选择设备功能"
                @change="(val) => updateFunctionParams(actuatorIndex, val)"
              >
                <a-select-option v-for="option in model.actuators[actuatorIndex].invokeFunction.functionOptions" :key="option.funcId">{{ option.funcName }}</a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item
              v-for="(param, paramIndex) in functionInputParams"
              v-if="model.triggerMethod && actuator.actuatorType === 2"
              :key="param.funcId"
              :label="param.name"
              @change=""
            >
              <a-input v-show="false" v-model="actuator.invokeFunction.params[paramIndex].dataId" />
              <a-input v-show="false" :defaultValue="param.code" />
              <a-input v-model="actuator.invokeFunction.params[paramIndex].value" :disabled="param.inputMode === 'ins_input'" />
            </a-form-model-item>
          </template>
        </a-card>
        <a href="#" style="margin: 10px 0 10px 0" @click="addActuator">
          <a-icon style="font-size: 18px; margin-right: 4px" type="plus" />
          新增执行动作
        </a>
        <!-- 执行器 end -->
        <a-form-model-item ref="description" label="说明" prop="description">
          <a-textarea v-model="model.description" placeholder="请输入说明" rows="4" />
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import {getAction, httpAction} from '@/api/manage'
import JSearchSelectTag from '@/components/dict/JSearchSelectTag'
import JCron from '@/components/jeecg/JCron'
import SimilarConfigModel from './SimilarConfigModel'

export default {
  name: 'DeviceAlarmConfigModal',
  components: {
    SimilarConfigModel,
    JSearchSelectTag,
    JCron
  },
  computed: {
    configName() {
      return this.model.configName
    },
    instanceId() {
      return this.model.instanceId
    },
    triggerMethod() {
      return this.model.triggerMethod
    },
    triggers() {
      return this.model.triggers
    },
    actuators() {
      return this.model.actuators
    }
  },
  watch: {
    instanceId(val, oval) {
      console.log('watch-instanceId', oval, '=>', val)
      if (val && !this.disableSubmit) {
        this.querySimilarConfig(val)
        this.loadModelDatas(val)
      } else {
        this.isImportConfig = false
      }
    },
    triggerMethod(val, oval) {
      let scoped = this
      console.log('watch-triggerMethod', oval, '=>', val)
      if (val) {
        if (val === 'timer') {
          for (let trigger of this.model.triggers) {
            trigger.source = 'data_receive'
            scoped.sourceOptions
              .filter(sourceOption => sourceOption.code !== 'data_receive')
              .map(sourceOption => {
                sourceOption['disabled'] = true
              })
          }
        } else {
          for (let trigger of this.model.triggers) {
            scoped.sourceOptions
              .map(sourceOption => {
                sourceOption['disabled'] = false
              })
          }
        }
      }
    },
    triggers: {
      handler(val, oval) {
        console.log('watch-triggers', oval, '=>', val)
        if (!oval && val) {
          for (let i = 0; i < val.length; i++) {
            // 表单加载时
            console.log('watch-triggers[' + i + ']', oval, '=>', val[i])
            /* 定时判断this.modelDataOptions的长度 */
            let timer = window.setInterval(() => {
              if (this.modelDataOptions.length > 0) {
                this.updateFilterRule(i, val[i].modelDataId)
                window.clearInterval(timer)
              }
            }, 100)
          }
        }
      }
    },
    actuators: {
      handler(val, oval) {
        console.log('watch-actuators', oval, '=>', val)
        if (!oval && val) {
          for (let i = 0; i < val.length; i++) {
            // 表单加载时
            console.log('watch-actuators[' + i + ']', oval, '=>', val[i])
            // 功能调用时
            if (val[i].actuatorType === 2) {
              this.updateDeviceFunction(i, val[i].invokeFunction.instanceId).then(res => {
                this.updateFunctionParams(i, val[i].invokeFunction.functionId)
              }).catch(err => {
                console.log(err)
              })
            }
          }
        }
      },
      deep: true
    }
  },
  data() {
    return {
      title: '操作',
      width: 800,
      visible: false,
      disableSubmit: false,
      instanceIdDisable: false,
      instanceTreeOptions: [],
      sourceOptions: [],
      ruleConditionOptions: [],
      modelDataOptions: [],
      actuatorTypeOptions: [],
      noticeTypeOptions: [],
      noticeConfigOptions: [],
      deviceFunctionOptions: [],
      functionInputParams: [],
      instanceSource: [],
      noticeTemplates: [],
      baseModel: {
        instanceId: '',
        alarmLevel: 1,
        isDeal: false,
        triggerMatchType: 'any',
        triggers: [{
          name: '触发规则1',
          isNameEdit: false,
          filters: [{}],
          filterRuleOptions: []
        }],
        actuators: [{
          name: '执行动作1',
          isNameEdit: false,
          actuatorType: '',
          notification: {
            noticeType: undefined,
            noticeConfigId: '',
            noticeTemplateCode: ''
          },
          invokeFunction: {
            functionId: '',
            functionOptions: [],
            instanceId: '',
            params: [{}]
          },
          dataForward: {}
        }]
      },
      isImportConfig: false,
      model: {},
      labelCol: {
        xs: {span: 24},
        sm: {span: 5}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16}
      },
      confirmLoading: false,
      rules: {
        name: [
          { required: true, message: '请输入告警名称!' },
          { min: 3, max: 30, message: '实例告警长度为3-30个字符' }
        ],
        instanceId: [
          { required: true, message: '请选择设备实例!' }
        ],
        triggerType: [
          { required: true, message: '请选择触发方式!' }
        ]
      },
      url: {
        add: 'alarm/config/add',
        edit: 'alarm/config/edit',
        getConfigForm: 'alarm/config/queryWholeById',
        instanceTree: 'device/instance/listTree',
        getSources: 'alarm/trigger/listMessageEventType',
        getRuleCondition: 'alarm/trigger/listRuleCondition',
        getModelDatas: 'device/model/queryDataByInstanceId',
        getActuatorType: 'alarm/config/getActuatorType',
        getNoticeType: 'alarm/config/getNoticeType',
        getFunction: 'device/instance/getExtendParams'
      }
    }
  },
  mounted() {
    this.loadInstances()
    this.loadSources()
    this.getRuleCondition()
    this.getActuatorType()
    this.getNoticeType()
  },
  methods: {
    importConfig(configId) {
      this.edit({id: configId}, this.model.id, this.model.instanceId)
    },
    // 查询相似配置
    querySimilarConfig(instanceId) {
      let score = this
      getAction(`/alarm/config/querySameLevelByInstanceId/${instanceId}`).then(data => {
        if (data.success) {
          if (data.result.length > 0) {
            score.isImportConfig = true
            score.instanceSource = data.result
          } else {
            score.isImportConfig = false
          }
        }
      })

    },
    updateFunctionParams(actuatorIndex, functionId) {
      let scope = this
      if (functionId) {
        this.functionInputParams =
          this.model.actuators[actuatorIndex].invokeFunction.functionOptions.filter(func => func.funcId === functionId)[0].inputParams
      }
      this.functionInputParams.map((param, index) => {
        console.log(param, index)
        this.model.actuators[actuatorIndex].invokeFunction.params[index].dataId = param.id
        this.model.actuators[actuatorIndex].invokeFunction.params[index].value = param.value
      })
    },
    updateDeviceFunction(actuatorIndex, instanceId) {
      let scope = this
      console.log(actuatorIndex, instanceId)
      // scope.model.actuators[actuatorIndex].invokeFunction.functionId = undefined
      // scope.model.actuators[actuatorIndex].invokeFunction.params = [{}]
      return new Promise((resolve, reject) => {
        if (!instanceId) {
          return reject(`instanceId is null`)
        }
        getAction(this.url.getFunction, {id: instanceId}).then(res => {
          if (res.success) {
            scope.model.actuators[actuatorIndex].invokeFunction.functionOptions = res.result
            scope.$forceUpdate()
            return resolve(res.result)
          }
        })
      })
    },
    updateFilterRule(triggerIndex, modelDataId) {
      console.log(`updateFilterRule(${triggerIndex}, ${modelDataId})`)
      this.model.triggers[triggerIndex].filterRuleOptions = []
      let modelDatas = this.modelDataOptions.filter(data => data.id === modelDataId)
      console.log(modelDatas)
      if (modelDatas.length > 0) {
        let currentModelData = modelDatas[0]
        let dataType = currentModelData.type
        if ('vector3'.indexOf(dataType) !== -1) {
          // 对象处理
          this.model.triggers[triggerIndex].filterRuleOptions.push(`${currentModelData.code}.x`)
          this.model.triggers[triggerIndex].filterRuleOptions.push(`${currentModelData.code}.y`)
          this.model.triggers[triggerIndex].filterRuleOptions.push(`${currentModelData.code}.z`)
        } else {
          // 单个数据
          this.model.triggers[triggerIndex].filterRuleOptions.push(currentModelData.code)
        }
        this.$forceUpdate()
      }
      console.log(this.model.triggers[triggerIndex].filterRuleOptions)
    },
    getNoticeType() {
      let scope = this
      getAction(this.url.getNoticeType).then(res => {
        if (res.success) {
          scope.noticeTypeOptions = res.result
        }
      })
    },
    getActuatorType() {
      let scope = this
      getAction(this.url.getActuatorType).then(res => {
        if (res.success) {
          scope.actuatorTypeOptions = res.result
        }
      })
    },
    getSysMsgTemplate(tempType) {
      console.log('消息类型', tempType, this.noticeTemplates[tempType])
      let scope = this
      getAction(`alarm/config/querySysMsgTemplate/${tempType}`).then(data => {
        if (data.success) {
          scope.noticeTemplates = data.result
        }
      })
    },
    addRowRule(triggerIndex) {
      this.model.triggers[triggerIndex].filters.push({})
      this.$forceUpdate()
    },
    delRowRule(triggerIndex, ruleIndex) {
      console.log(ruleIndex)
      this.model.triggers[triggerIndex].filters.splice(ruleIndex, 1)
      this.$forceUpdate()
    },
    loadModelDatas(instanceId) {
      let scoped = this
      getAction(this.url.getModelDatas, { instanceId: instanceId }).then(res => {
        if (res.success) {
          scoped.modelDataOptions = res.result
        }
      })
    },
    loadSources() {
      let scoped = this
      getAction(this.url.getSources).then(res => {
        if (res.success) {
          scoped.sourceOptions = res.result.filter(source => source.code.indexOf('network') === -1)
        }
      })
    },
    getRuleCondition() {
      let scoped = this
      getAction(this.url.getRuleCondition).then(res => {
        if (res.success) {
          scoped.ruleConditionOptions = res.result
        }
      })
    },
    addTrigger() {
      this.model.triggers.push({
        name: '触发规则' + (this.model.triggers.length + 1),
        isNameEdit: false,
        filters: [{}]
      })
    },
    deleteTrigger(triggerIndex) {
      this.model.triggers.splice(triggerIndex - 0, 1)
      this.model.triggers.forEach((trigger, index) => {
        if (parseFloat(trigger.name.substr(trigger.name.length - 1, 1)).toString() !== 'NaN') {
          trigger.name = trigger.name.substring(0, trigger.name.length - 1) + (index + 1)
        }
      })
    },
    addActuator() {
      let baseModel = JSON.parse(JSON.stringify(this.baseModel))
      this.model.actuators.push(Object.assign(baseModel.actuators[0], {
        name: '执行动作' + (this.model.actuators.length + 1),
        isNameEdit: false
      }))
    },
    deleteActuator(actuatorIndex) {
      this.model.actuators.splice(actuatorIndex - 0, 1)
      this.model.actuators.forEach((actuator, index) => {
        if (parseFloat(actuator.name.substr(actuator.name.length - 1, 1)).toString() !== 'NaN') {
          actuator.name = actuator.name.substring(0, actuator.name.length - 1) + (index + 1)
        }
      })
    },
    loadInstances() {
      getAction(this.url.instanceTree).then(res => {
        if (res.success) {
          this.instanceTreeOptions = res.result
        }
      })
    },
    add(instanceId) {
      this.model = JSON.parse(JSON.stringify(this.baseModel))
      this.model['instanceId'] = instanceId
      console.log(this.model)
      if (!instanceId) {
        this.instanceIdDisable = false
      }
      this.visible = true
    },
    detail(configId) {
      this.disableSubmit = true
      this.edit(configId)
    },
    edit(configId, oldId = undefined, oldInstanceId = undefined) {
      let scope = this
      if (!configId) {
        return
      }
      getAction(this.url.getConfigForm, {id: configId}).then(res => {
        if (res.success) {
          scope.model = Object.assign({}, res.result)
          let baseModel = JSON.parse(JSON.stringify(scope.baseModel))
          scope.model.triggers.map(trigger => {
            Object.assign(baseModel.triggers[0], trigger)
          })
          scope.model.actuators.map(actuator => {
            Object.assign(baseModel.actuators[0], actuator)
          })

          // 导入时，使用原始实例id
          if (oldInstanceId) {
            scope.model.instanceId = oldInstanceId
            scope.model.id = oldId
          }
          console.log(scope.model)
          console.log(scope.baseModel)
        }
      })
      this.visible = true
    },
    close() {
      this.model = {}
      this.isImportConfig = false
      this.$refs.alarmConfigForm.resetFields()
      this.$emit('close')
      this.visible = false
      this.disableSubmit = false
      this.$forceUpdate()
    },
    handleOk() {
      const self = this
      // 触发表单验证
      this.$refs.alarmConfigForm.validate(valid => {
        if (valid) {
          self.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          console.log(this.model)
          httpAction(httpurl, this.model, method)
            .then(res => {
              if (res.success) {
                self.$message.success(res.message)
                self.$emit('ok')
              } else {
                self.$message.warning(res.message)
              }
            })
            .finally(() => {
              self.confirmLoading = false
              self.$refs.alarmConfigForm.resetFields()
              self.close()
            })
        } else {
          return false
        }
      })
    },
    handleCancel() {
      this.close()
    }
  }
}
</script>

<style scoped>
.trigger-name {

}
</style>